<template>
  <view class="clock">
    <map
      style="width: 100%; height: 442rpx"
      :latitude="local.latitude"
      :longitude="local.longitude"
      :markers="local.markers"
      :scale="16"
    />
    <view class="clock-title">
      <uv-text :text="local.name || '正在获取'" size="32rpx" color="#212121" lines="1" />
      <view class="clock-row">
        <uv-text
          :text="local.address || '正在获取'"
          size="24rpx"
          color="#BDBDBD"
          lines="1"
        />
        <text @click="handleLoacl">纠正位置</text>
      </view>
    </view>
    <uv-gap height="20rpx" bgColor="#f5f5f5" />
    <view class="clock-user">
      <view class="clock-user-title"> <text style="color: #f00">*</text> 关联客户 </view>
      <view class="clock-user-content">
        {{ local.customerName || "--" }}
        <uv-icon name="arrow-right" color="#757575" size="28rpx" />
      </view>
    </view>
    <uv-gap height="20rpx" bgColor="#f5f5f5" />
    <view class="clock-in">
      <uv-steps
        v-if="signHistory.length > 0"
        dot
        :current="
          signHistory[signHistory.length - 1]?.id
            ? signHistory.length - 1
            : signHistory.length - 2
        "
        active-color="#4EA770"
        inactive-color="#DEDEDE"
        direction="column"
        :custom-style="{
          padding: '30rpx',
        }"
      >
        <uv-steps-item
          v-for="(item, index) in signHistory"
          :key="index"
          :title="item.type == 1 ? '启动卡' : '结束卡'"
        >
          <template #desc>
            <view class="clock-in-desc">
              <uv-text
                v-if="item.createTime"
                :text="`打卡时间：${timeFormat(
                  Number(new Date(item.createTime)),
                  'hh:MM:ss'
                )}`"
                color="#757575"
                prefixIcon="clock"
                icon-style="font-size: 28rpx; color: #757575; margin-right: 20rpx"
                size="28rpx"
              />
              <uv-text
                v-if="item.address"
                :text="item.address"
                color="#757575"
                prefixIcon="map"
                icon-style="font-size: 28rpx; color: #757575; margin-right: 20rpx"
                size="28rpx"
                margin="0 0 30rpx 0"
              />
              <text
                v-if="
                  signHistory[signHistory.length - 1]?.id
                    ? signHistory.length - 1 == index
                    : signHistory.length - 2 == index
                "
                @click="handleUpdateSign(item)"
              >
                更新打卡
              </text>
            </view>
          </template>
        </uv-steps-item>
      </uv-steps>
      <view v-else class="clock-in-title">外勤打卡</view>
      <!-- :auth="forms.type == 1" -->
      <g-sign-btn
        label="工作打卡"
        :auth="false"
        :near="nearRange"
        @confirm="handleWork"
      />
    </view>
    <uv-gap height="180rpx" />
    <uv-modal
      ref="modelRef"
      confirm-text="我知道了"
      confirm-color="#4EA770"
      @confirm="handleSuccess"
      @close="handleSuccess"
    >
      <view>
        <uv-image src="/static/sign/icon_success.png" width="288rpx" height="272rpx" />
        <uv-text
          :text="nowTime"
          size="56rpx"
          color="#333333"
          align="center"
          margin="0 0 20rpx 0"
        />
        <uv-text text="打卡成功" size="32rpx" color="#333333" align="center" />
      </view>
    </uv-modal>
    <uv-modal
      ref="tipsRef"
      confirm-text="确定"
      confirm-color="#4EA770"
      :show-cancel-button="tipsCode == 1"
      @confirm="confirmUpdate"
      @cancel="cancelUpdate"
    >
      <uv-text v-if="tipsCode == 1" :text="tipsMsg" margin="50rpx auto" align="center" />
      <view v-if="tipsCode == 2" class="tips-box">
        <uv-image src="/static/sign/icon_error.png" width="110rpx" height="110rpx" />
        <uv-text text="打卡失败" margin="20rpx auto" align="center" />
        <uv-text :text="tipsMsg" align="center" />
      </view>
    </uv-modal>
  </view>
</template>
<script setup>
import { onMounted, ref, watch } from "vue";
import { timeFormat } from "@/common/mothed.js";
import {
  requestAndroidPermission,
  gotoAppPermissionSetting,
} from "@/common/permission.js";
import { addClockInRecord, updateClockInRecord, getClockInList } from "@/request/home";
import { projectDetail, isClockInRange } from "@/request/task";
import iconMap from "@/static/sign/icon_map.png";

const forms = ref({
  maintenanceSubPlanId: 0, // 任务ID
  type: 1, // 打卡类型 1启动卡 2结束卡
  latitude: 0, // 打卡纬度
  longitude: 0, // 打卡经度
  address: "", // 打卡地址
  createTime: "", // 打卡时间
});
const local = ref({}); // 当前位置
const modelRef = ref(); // 弹窗ref
const nowTime = ref(); // 当前时间
const signHistory = ref([]); // 打卡历史
const tipsRef = ref(); // 提示弹窗ref
const tipsCode = ref("1"); // 提示弹窗code
const tipsMsg = ref("确认要更新此次打卡记录吗？");
const nearRange = ref(false); // 是否在范围内

const props = defineProps({
  // 工单id
  subPlanId: {
    type: [String, Number],
    default: "",
  },
});

watch(
  props,
  (v) => {
    if (v.subPlanId) {
      setTimeout(() => {
        forms.value.maintenanceSubPlanId = v.subPlanId;
        getClockList();
        // #ifdef APP-PLUS
        isGetLocation();
        // #endif
        // #ifdef H5
        getLoacl();
        // #endif
      }, 300);
    }
  },
  { immediate: true, deep: true }
);

onMounted(() => {
  uni.setNavigationBarTitle({ title: "签到打卡" });
});

// 检测位置权限
const isGetLocation = async () => {
  var result = await requestAndroidPermission("android.permission.ACCESS_FINE_LOCATION");
  if (result == 1) {
    getLoacl();
  } else if (result == 0) {
    gotoAppPermissionSetting();
  }
};

// 获取当前位置
const getLoacl = () => {
  projectDetail(forms.value.maintenanceSubPlanId).then((res) => {
    if (res.code == 200) {
      const { customerName, latitude, longitude } = res.data;
      getPos(customerName, latitude, longitude);
    }
  });
};

// 获取当前位置
const getPos = (customerName, latitude, longitude) => {
  uni.getLocation({
    type: "gcj02",
    // #ifdef APP-PLUS
    geocode: true,
    // #endif
    success: (pos) => {
      console.log("当前位置：", pos);
      forms.value.latitude = pos.latitude;
      forms.value.longitude = pos.longitude;
      // #ifdef APP-PLUS
      forms.value.address = pos.address?.poiName;
      // #endif
      local.value = {
        customerName: customerName,
        // #ifdef APP-PLUS
        name: pos.address?.poiName,
        address: pos.address?.street + pos.address?.poiName + pos.address?.streetNum,
        // #endif
        latitude: pos.latitude,
        longitude: pos.longitude,
        markers: [
          {
            id: 1,
            latitude: latitude,
            longitude: longitude,
            title: pos.name,
            iconPath: iconMap,
            width: 18,
            height: 22,
          },
          {
            id: 2,
            latitude: pos.latitude,
            longitude: pos.longitude,
            title: pos.name,
            iconPath: iconMap,
            width: 18,
            height: 22,
          },
        ],
      };
      checkClockInRange();
    },
    fail: (e) => {
      console.log("获取授权失败：", e);
      setTimeout(() => {
        getPos(customerName, latitude, longitude);
      }, 1000);
    },
  });
};

// 获取打卡历史记录
const getClockList = () => {
  getClockInList({
    subPlanId: forms.value.maintenanceSubPlanId,
    time: timeFormat(Number(new Date())),
  }).then((res) => {
    if (res.code == 200) {
      let list = res.rows || [];
      list = list.reverse();
      if (list.length && list[list.length - 1].type == 1) {
        forms.value.type = 2;
        list.push({ type: 2 });
      } else {
        forms.value.type = 1;
      }
      signHistory.value = list;
    }
  });
};

// 工作打卡
const handleWork = (date) => {
  uni.$uv?.throttle(() => {
    forms.value.createTime = date;
    addClockInRecord(forms.value).then((res) => {
      if (res.code == 200) {
        nowTime.value = timeFormat(Number(new Date()), "hh:MM:ss");
        modelRef.value.open();
        uni.$emit("Task-Cache", {
          subPlanId: forms.value.maintenanceSubPlanId,
          type: forms.value.type,
        });
      } else if (res.code == 1002) {
        tipsCode.value = 2;
        tipsMsg.value = res.msg;
        tipsRef.value.open();
      }
    });
  }, 1000);
};

// 检测是否在打卡范围内
const checkClockInRange = () => {
  let data = {
    resourceId: props.subPlanId,
    latitude: local.value.latitude,
    longitude: local.value.longitude,
  };
  isClockInRange(data).then((res) => {
    if (res.code == 200) {
      nearRange.value = res.data;
    }
  });
};

// 打卡成功
const handleSuccess = () => {
  uni.navigateBack({ delta: forms.value.type });
};

// 纠正位置
const handleLoacl = () => {
  uni.showLoading({
    title: "请稍等..",
    mask: true,
  });
  uni.getLocation({
    type: "gcj02",
    // #ifdef APP-PLUS
    geocode: true,
    // #endif
    success: (pos) => {
      console.log("当前位置：", pos);
      uni.hideLoading();
      uni.chooseLocation({
        latitude: pos.latitude,
        longitude: pos.longitude,
        success: (res) => {
          forms.value.address = pos.address?.poiName;
          local.value = {
            name: res.name,
            customerName: local.value.customerName,
            address: pos.address?.street + pos.address?.poiName + pos.address?.streetNum,
            latitude: pos.latitude,
            longitude: pos.longitude,
            markers: [
              {
                id: 1,
                latitude: pos.latitude,
                longitude: pos.longitude,
                title: res.name,
                iconPath: iconMap,
                width: 18,
                height: 22,
              },
            ],
          };
          checkClockInRange();
        },
      });
    },
    fail: (e) => {
      console.log("获取授权失败：", e);
      uni.hideLoading();
      setTimeout(() => {
        handleLoacl();
      }, 1000);
    },
  });
};

// 更新打卡
const handleUpdateSign = (item) => {
  tipsCode.value = 1;
  tipsMsg.value = "确认要更新此次打卡记录吗？";
  forms.value.id = item.id;
  forms.value.type = item.type;
  forms.value.maintenanceSubPlanId = item.maintenanceSubPlanId;
  forms.value.createTime = timeFormat(null, "yyyy-mm-dd hh:MM:ss");
  tipsRef.value.open();
};

// 提示弹窗
const confirmUpdate = () => {
  tipsRef.value.close();
  if (tipsCode.value == 1) {
    updateClockInRecord(forms.value).then((res) => {
      if (res.code == 200) {
        nowTime.value = timeFormat(Number(new Date()), "hh:MM:ss");
        modelRef.value.open();
      } else if (res.code == 1002) {
        tipsCode.value = 2;
        tipsMsg.value = res.msg;
        tipsRef.value.open();
      }
    });
  } else {
    tipsRef.value.close();
  }
};

// 取消更新打卡
const cancelUpdate = () => {
  tipsRef.value.close();
  delete forms.value.id;
  forms.value.type = signHistory.value[signHistory.value.length - 1].type;
};
</script>
<style lang="scss" scoped>
.clock {
  .clock-title {
    height: 140rpx;
    background-color: #fff;
    padding: 20rpx 40rpx;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .clock-row {
      display: flex;
      justify-content: space-between;
      > text {
        font-size: 24rpx;
        color: #4ea770;
      }
    }
  }
  .clock-user {
    height: 100rpx;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 40rpx;
    &-title {
      font-size: 28rpx;
      color: #212121;
    }
    &-content {
      max-width: 520rpx;
      font-size: 28rpx;
      color: #757575;
      display: flex;
    }
  }
  .clock-in {
    background-color: #fff;
    position: relative;
    .clock-in-title {
      position: absolute;
      top: 0;
      height: 100rpx;
      color: #757575;
      font-size: 28rpx;
      margin-left: 40rpx;
      display: flex;
      align-items: center;
      &::before {
        content: "";
        display: inline-block;
        width: 20rpx;
        height: 20rpx;
        border-radius: 50%;
        margin-right: 20rpx;
        background-color: #4ea770;
      }
    }
    .clock-in-desc {
      padding-bottom: 40rpx;
      text {
        font-size: 28rpx;
        color: #4ea770;
      }
    }
  }
}
.tips-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
</style>
